//
//  CheckUpdate.swift
//  CheckApp
//
//  Created by Ana Carolina on 13/11/20.
//  Copyright © 2020 acarolsf. All rights reserved.
//

import Foundation
import UIKit

class AppStoreAppVersionCheckUpdater: NSObject {
    
    enum VersionError: Error {
        case invalidBundleInfo, invalidResponse
    }
    
    class LookupResult: Decodable {
        var results: [AppInfo]
    }
    
    class AppInfo: Decodable, CustomStringConvertible {
        /// 版本号
        var version: String
        /// 链接
        var trackViewUrl: String
        /// 更新说明
        var releaseNotes: String?
        
        var description: String {
            "{ version = \(version), trackViewUrl = \(trackViewUrl), releaseNotes = \(releaseNotes ?? "") }"
        }
        
        init() {
            version = ""
            trackViewUrl = ""
            releaseNotes = ""
        }
    }
    
    static let shared = AppStoreAppVersionCheckUpdater()
    
//    func showUpdate(withConfirmation: Bool) {
//        DispatchQueue.global().async {
//            self.checkVersion(force : !withConfirmation)
//        }
//    }
    
//    private func checkVersion(force: Bool) {
//        if let currentVersion = self.getBundle(key: "CFBundleShortVersionString") {
//            _ = getAppInfo { (info, error) in
//                if let appStoreAppVersion = info?.version {
//                    if let error = error {
//                        print("error getting app store version: ", error)
//                    } else if appStoreAppVersion <= currentVersion {
//                        print("Already on the last app version: ",currentVersion)
//                    } else {
//                        print("Needs update: AppStore Version: \(appStoreAppVersion) > Current version: ",currentVersion)
//                        DispatchQueue.main.async {
//                            let topController: UIViewController = (UIApplication.shared.windows.first?.rootViewController)!
//                            topController.showAppUpdateAlert(Version: (info?.version)!, Force: force, AppURL: (info?.trackViewUrl)!)
//                        }
//                    }
//                }
//            }
//        }
//    }
    
    func checkVersion(completion: ((AppInfo?) -> Void)?) {
        guard let currentVersion = getAppCurrentVersion() else {
            completion?(nil)
            return
        }
        
        _ = getAppInfo { (info, error) in
            DispatchQueue.main.async {
                guard let appInfo = info else {
                    log.error("error getting app store version: \(String(describing: error))")
                    completion?(nil)
                    return
                }
                let appStoreAppVersion = appInfo.version
                if appStoreAppVersion <= currentVersion {
                    completion?(nil)
                    return
                }
//                let isOk = Self.isAppCanUpdate(localVersion: currentVersion, serverVersion: appStoreAppVersion)
//                if !isOk {
//                    completion?(nil)
//                    return
//                }
                
                completion?(appInfo)
            }
        }
    }
    
    func getAppCurrentVersion() -> String? {
        let currentVersion = getBundle(key: "CFBundleShortVersionString")
        
        return currentVersion
    }
    
    private func getAppInfo(completion: @escaping (AppInfo?, Error?) -> Void) -> URLSessionDataTask? {
        // You should pay attention on the country that your app is located, in my case I put Brazil */br/*
        // Você deve prestar atenção em que país o app está disponível, no meu caso eu coloquei Brasil */br/*
        
        guard let identifier = self.getBundle(key: "CFBundleIdentifier"),
              let url = URL(string: "http://itunes.apple.com/br/lookup?bundleId=\(identifier)") else {
            DispatchQueue.main.async {
                completion(nil, VersionError.invalidBundleInfo)
            }
            return nil
        }
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            do {
                if let error = error { throw error }
                guard let data = data else { throw VersionError.invalidResponse }
                
                let result = try JSONDecoder().decode(LookupResult.self, from: data)
//                let jsonResult = try JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed, .mutableContainers])
                log.info("获取 AppStore App 版本信息: \(result.results) \n")

                guard let info = result.results.first else {
                    throw VersionError.invalidResponse
                }

                completion(info, nil)

                // Test
//                let testInfo = AppInfo()
//                testInfo.version = "1.0.1"
//                testInfo.releaseNotes = "1.1111 \n2.3fsafef\n"
//
//                completion(testInfo, nil)
            } catch {
                log.error("获取 AppStore App 版本信息出错 error = \(error) \n")
                completion(nil, error)
            }
        }
        
        task.resume()
        return task
        
    }
    
    func getBundle(key: String) -> String? {
        guard let filePath: String = Bundle.main.path(forResource: "Info", ofType: "plist") else {
            fatalError("Couldn't find file 'Info.plist'.")
        }
        // 2 - Add the file to a dictionary
        let plist = NSDictionary(contentsOfFile: filePath)
        // Check if the variable on plist exists
        guard let value = plist?.object(forKey: key) as? String else {
            fatalError("Couldn't find key '\(key)' in 'Info.plist'.")
        }
        return value
    }
    
//    private class func isAppCanUpdate(localVersion: String, serverVersion: String) -> Bool {
//        let tReqVersion = localVersion.replacingOccurrences(of: "V", with: "", options: .caseInsensitive)
//        let tServerVersion = serverVersion.replacingOccurrences(of: "V", with: "", options: .caseInsensitive)
//
//        let tReqArray = tReqVersion.components(separatedBy: ".")
//        let tServerArray = tServerVersion.components(separatedBy: ".")
//
//        var ret = false
//        if tReqArray.count >= tServerArray.count {
//            for i in 0..<tServerArray.count {
//                guard let iReq = Int(tReqArray[i]), let iServer = Int(tServerArray[i]) else {
//                    ret = false
//                    break
//                }
//
//                if iReq < iServer {
//                    ret = true
//                    break
//                }
//            }
//        } else {
//            ret = true
//        }
//
//        log.info("checkAppVersion ret = \(ret), tReqArray = \(tReqArray), tServerArray = \(tServerArray) \n")
//
//        return ret
//    }
    
}

//extension UIViewController {
//
//    @objc fileprivate func showAppUpdateAlert( Version : String, Force: Bool, AppURL: String) {
//        guard let appName = AppStoreAppVersionCheckUpdater.shared.getBundle(key: "CFBundleName") else { return } //Bundle.appName()
//
//        let alertTitle = "New version"
//        let alertMessage = "A new version of \(appName) is available on AppStore. Update now!"
//
//        let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
//
//        if !Force {
//            let notNowButton = UIAlertAction(title: "Not now", style: .default)
//            alertController.addAction(notNowButton)
//        }
//
//        let updateButton = UIAlertAction(title: "Update", style: .default) { (action:UIAlertAction) in
//            guard let url = URL(string: AppURL) else {
//                return
//            }
//            if #available(iOS 10.0, *) {
//                UIApplication.shared.open(url, options: [:], completionHandler: nil)
//            } else {
//                UIApplication.shared.openURL(url)
//            }
//        }
//
//        alertController.addAction(updateButton)
//        self.present(alertController, animated: true, completion: nil)
//    }
//
//}

